package com.photolibrary.base;


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by ch
 * on 2017/12/19.14:24
 * 作用：
 */

public abstract class BaseRecAdapter<T, K extends BaseRecViewHolder> extends RecyclerView.Adapter<K> {

    private List<T> list;
    private onItemClickListener itemClickListener;
    private Context context;

    public onItemClickListener getItemClickListener() {
        return itemClickListener;
    }

    public void setItemClickListener(onItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public BaseRecAdapter(List<T> list) {
        this.list = list;
    }

    @Override
    public K onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        return onCreateHolder();
    }

    @Override
    public void onBindViewHolder(K holder, int position) {

        onHolder(holder, list.get(position), position);
        //绑定listener
        bindListener(holder, position);
    }


    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }


    /**
     * 填充数据
     *
     * @param holder
     * @param position
     */
    public abstract void onHolder(K holder, T bean, int position);


    public abstract K onCreateHolder();


    /**
     * 通过资源res获得view
     *
     * @param res
     * @return
     */
    public View getViewByRes(int res) {
        return LayoutInflater.from(context).inflate(res, null);
    }

    private void bindListener(K holder, final int position) {
        if (holder != null) {
            View itemView = holder.itemView;
            if (itemView != null) {
                if (getItemClickListener() != null) {
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getItemClickListener().onItemClick(BaseRecAdapter.this, v, position);
                        }
                    });
                }

            }
        }
    }


    public interface onItemClickListener {
        void onItemClick(BaseRecAdapter adapter, View view, int position);
    }


}
